import { useCallback, useState, useMemo } from 'react';
import InputLimit, { InputLimitProps } from '../InputLimit';
import { countDown } from '../../utils/common';
import styles from './index.module.less';

export interface InputVeriCodeProps extends InputLimitProps {
  count?: number;
  onGetVerCode: () => Promise<boolean>;
}

/**
 * 验证码组件
 * @param {*} props
 * @returns
 */
export default function InputVeriCode(props: InputVeriCodeProps) {
  const { count = 60, onGetVerCode, ...inputLimitProps } = props;

  const [con, setCon] = useState(0);
  const [isFirst, setFirst] = useState(true);
  const isCounting = useMemo(() => con > 0, [con]);

  const doClick = useCallback(() => {
    onGetVerCode().then((success) => {
      if (success) {
        countDown((curCon) => {
          setCon(curCon);
          setFirst(false);
        }, count);
      }
    });
  }, [onGetVerCode]);

  return (
    <InputLimit
      {...inputLimitProps}
      suffix={
        <div className={isCounting ? styles.count : styles.noCount} onClick={() => !isCounting && doClick()}>
          {isCounting ? `${con}秒后重新获取` : isFirst ? '获取验证码' : '重新获取验证码'}
        </div>
      }
    />
  );
}
